﻿using System.Collections.Generic;
using System.Linq;
using ZilLion.Service.Core.DapperWrapper;
using ZilLion.Service.Core.DapperWrapper.SqlServer;
using ZilLion.Service.WeChatMall.Domain.Entitys.Orders;
using ZilLion.Service.WeChatMall.Domain.Repositorys.Interface.Order;

namespace ZilLion.Service.WeChatMall.Domain.Repositorys.Order
{
    public class PrePayOrderDetailRepository : SqlServerRespository<PrePayOrderDetailEntity>,
        IPrePayOrderDetailRepository
    {
        public PrePayOrderDetailRepository()
        {
            Context = new WechatMallContext();
        }

        public IList<PrePayOrderDetailEntity> GetOrderDetails(string sno)
        {
            var beginsn = sno + "000";
            var endsn = sno + "zzz";
            var querysql = DapperHelper.CreateColSqlByMap<PrePayOrderDetailEntity>();
            var sql =
                $@"SELECT {querysql}
                FROM    weiscdzfdddt 
                where dddmxhh>=@beginsn and dddmxhh<=@endsn";


            return GetList(sql, new { beginsn, endsn }).ToList();
        }

        public IList<PrePayOrderDetailEntity> GetOrderDetails(IList<string> snolist)
        {
            var condition = snolist.Aggregate(string.Empty, (current, sno) => current + sno + ",");
            if (condition.EndsWith(","))
                condition = condition.Left(condition.Length - 1);
            var querysql = DapperHelper.CreateColSqlByMap<PrePayOrderDetailEntity>();
            var sql =
                $@"SELECT {querysql}
                FROM    weiscdzfdddt a
                INNER JOIN SplitString('{
                        condition
                    }',',',1) b ON a.dddmxhh>=b.value+'000' AND a.dddmxhh<=b.value+'zzz'";
            return GetList(sql).ToList();
        }

        public void SaveOrderDetailBatch(IList<PrePayOrderDetailEntity> entitys, OrderMainInfoDto orderMain,
            UnitOfWork unit = null)
        {
            var beginsn = orderMain.Sno + "000";
            var endsn = orderMain.Sno + "zzz";
            DapperHelper.Execute("delete from weiscdzfdddt where dddmxhh>=@beginsn and dddmxhh<=@endsn", Context, unit,
                new { beginsn, endsn });

            foreach (var entity in entitys)
                Add(entity, unit);
        }

        public void RemoveOrderDetailBatch(string sno, UnitOfWork unit = null)
        {
            var beginsn = sno + "000";
            var endsn = sno + "zzz";
            DapperHelper.Execute("delete from weiscdzfdddt where dddmxhh>=@beginsn and dddmxhh<=@endsn", Context, unit,
                new { beginsn, endsn });
        }
    }
}